package com.xqb.modules.controller.course;

import com.xqb.common.annotation.Log;
import com.xqb.common.core.controller.BaseController;
import com.xqb.common.core.domain.AjaxResult;
import com.xqb.common.enums.BusinessType;
import com.xqb.common.utils.SecurityUtils;
import com.xqb.common.utils.poi.ExcelUtil;
import com.xqb.modules.domain.dto.LesInterestsDto;
import com.xqb.modules.domain.dto.TreeNodeDto;
import com.xqb.modules.domain.po.LesCategory;
import com.xqb.modules.domain.po.LesInterests;
import com.xqb.modules.service.ILesCategoryService;
import com.xqb.modules.service.ILesInterestsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户兴趣Controller
 * 
 * @author xqb
 * @date 2024-10-14
 */
@RestController
@Slf4j
@RequestMapping("/course/interests")
public class LesInterestsController extends BaseController
{
    @Autowired
    private ILesInterestsService lesInterestsService;
    @Autowired
    private ILesCategoryService lesCategoryService;

    /**
     * 查询用户兴趣列表
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('course:interests:list')") // 权限注解，检查当前用户是否有查看课程兴趣的权限
    @GetMapping("/list")
    public AjaxResult list() {
        Long userId = SecurityUtils.getUserId(); // 获取当前用户的ID
        // 通过用户ID查询用户的兴趣信息
        LesInterests lesInterests = lesInterestsService.selectLesInterestsById(userId);

        // 判断用户是否有兴趣信息
        if (lesInterests == null || lesInterests.getInterests() == null || lesInterests.getInterests().isEmpty()) {
            return success(); // 若用户没有兴趣信息，则返回空信息
        }

        // 获取用户的兴趣字符串，并分割成兴趣ID数组
        String interestsStr = lesInterests.getInterests();
        String[] interestIds = interestsStr.split(",");
        // 通过兴趣ID数组查询对应的兴趣类别信息
        List<LesCategory> lesCategories = lesCategoryService.selectByIds(interestIds);

        // 将兴趣类别信息转换为TreeNodeDto列表
        List<TreeNodeDto> interests = lesCategories.stream()
                .map(lesCategory -> {
                    TreeNodeDto treeNodeDto = new TreeNodeDto();
                    // 设置树节点的名称
                    treeNodeDto.setName(lesCategory.getName());
                    // 设置树节点的标签（即兴趣类别的ID）
                    treeNodeDto.setId(lesCategory.getId());
                    return treeNodeDto;
                })
                .collect(Collectors.toList());

        // 添加日志记录
        log.info("查询用户兴趣列表成功，用户ID：{}", userId);

        // 返回查询结果
        return success(interests);
    }


    /**
     * 导出用户兴趣列表
     */
    @PreAuthorize("@ss.hasPermi('course:interests:export')")
    @Log(title = "用户兴趣", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, LesInterests lesInterests)
    {
        List<LesInterests> list = lesInterestsService.selectLesInterestsList(lesInterests);
        ExcelUtil<LesInterests> util = new ExcelUtil<>(LesInterests.class);
        util.exportExcel(response, list, "用户兴趣数据");
    }

    /**
     * 获取用户兴趣详细信息
     */
    @PreAuthorize("@ss.hasPermi('course:interests:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(lesInterestsService.selectLesInterestsById(id));
    }

    /**
     * 新增用户兴趣
     */
    @PreAuthorize("@ss.hasPermi('course:interests:add')")
    @Log(title = "用户兴趣", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody LesInterests lesInterests)
    {

        return toAjax(lesInterestsService.insertLesInterests(lesInterests));
    }

    /**
     * 修改用户兴趣
     */
    @PreAuthorize("@ss.hasPermi('course:interests:edit')") // 权限校验，检查用户是否有修改用户兴趣的权限
    @Log(title = "用户兴趣", businessType = BusinessType.UPDATE) // 日志注解，记录操作日志，标题为"用户兴趣"，业务类型为更新
    @PutMapping // 使用PUT请求映射
    public AjaxResult edit(@RequestBody LesInterestsDto lesInterestsDto) // 接收前端发送的JSON数据，并映射到LesInterests对象
    {
        List<String> interestsIds = lesInterestsDto.getInterestsIds();
        log.info("用户兴趣列表：{}", interestsIds);
        Long userId = SecurityUtils.getUserId(); // 获取当前用户的ID
        // 查询当前用户是否存在兴趣信息
        LesInterests lesInterestsPo = lesInterestsService.selectLesInterestsById(userId);
        // 创建一个LesInterests对象
        LesInterests lesInterests = new LesInterests();
        // 设置用户ID
        lesInterests.setId(userId);
        // 将前端传来的兴趣ID列表转换为字符串，并设置到用户兴趣对象中
        lesInterests.setInterests(interestsIds.stream().map(String::valueOf).collect(Collectors.joining(",")));

        // 如果当前用户存在兴趣信息
        if (lesInterestsPo != null) {
            // 更新用户兴趣信息
            return toAjax(lesInterestsService.updateLesInterests(lesInterests));
        } else {
            // 如果当前用户不存在兴趣信息，则插入新的兴趣信息
            return toAjax(lesInterestsService.insertLesInterests(lesInterests));
        }
    }


    /**
     * 删除用户兴趣
     */
    @PreAuthorize("@ss.hasPermi('course:interests:remove')")
    @Log(title = "用户兴趣", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(lesInterestsService.deleteLesInterestsByIds(ids));
    }
}
